<template>
  <view class="vip-records">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">VIP购买记录</text>
    </view>
    
    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stats-card">
        <view class="stats-item">
          <text class="stats-value">{{ totalOrders }}</text>
          <text class="stats-label">总订单数</text>
        </view>
        <view class="stats-item">
          <text class="stats-value">¥{{ totalAmount }}</text>
          <text class="stats-label">累计消费</text>
        </view>
        <view class="stats-item">
          <text class="stats-value">{{ totalDays }}</text>
          <text class="stats-label">累计天数</text>
        </view>
      </view>
    </view>
    
    <!-- 筛选器 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          class="filter-tab" 
          :class="{ active: currentFilter === item.value }"
          v-for="item in filterOptions" 
          :key="item.value"
          @click="changeFilter(item.value)"
        >
          <text>{{ item.label }}</text>
        </view>
      </view>
    </view>
    
    <!-- 记录列表 -->
    <view class="records-list">
      <view 
        class="record-item" 
        v-for="(record, index) in filteredRecords" 
        :key="record.id"
        @click="viewOrderDetail(record)"
      >
        <view class="record-header">
          <view class="record-title">
            <text class="vip-type">{{ record.vip_type }}</text>
            <view class="status-badge" :class="record.status === 1 ? 'success' : (record.status === 2 ? 'cancelled' : (record.status === 3 ? 'expired' : 'pending'))">
              <text>{{ getStatusText(record.status) }}</text>
            </view>
          </view>
          <text class="record-time">{{ formatTime(record.create_time) }}</text>
        </view>
        
        <view class="record-content">
          <view class="record-info">
            <view class="info-row">
              <text class="info-label">订单号：</text>
              <text class="info-value">{{ record.order_no }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">支付金额：</text>
              <text class="info-value price">¥{{ record.amount }}</text>
            </view>
            <view class="info-row" v-if="record.duration">
              <text class="info-label">有效期：</text>
              <text class="info-value">{{ record.duration }}天</text>
            </view>
            <view class="info-row" v-if="record.expire_time">
              <text class="info-label">到期时间：</text>
              <text class="info-value">{{ formatTime(record.expire_time) }}</text>
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="record-actions">
            <view 
              class="action-btn" 
              v-if="record.status === 0"
              @click.stop="payOrder(record)"
            >
              <text>继续支付</text>
            </view>
            <view 
              class="action-btn secondary" 
              v-if="record.status === 0"
              @click.stop="cancelOrder(record)"
            >
              <text>取消订单</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="filteredRecords.length === 0 && !loading">
      <u-empty 
        mode="data" 
        text="暂无购买记录"
        textColor="#999"
        iconSize="120"
      ></u-empty>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !loading">
      <u-loadmore 
        :status="loadStatus" 
        @loadmore="loadMore"
        loadText="点击加载更多"
        loadingText="正在加载..."
        noMoreText="没有更多了"
      />
    </view>
  </view>
</template>

<script>
/**
 * VIP购买记录页面
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { getVipOrders, cancelVipOrder, requestPayment } from '@/api/vip'

export default {
  name: 'VipRecords',
  data() {
    return {
      loading: false,
      hasMore: true,
      loadStatus: 'loadmore',
      page: 1,
      pageSize: 20,
      
      // 统计数据
      totalOrders: 0,
      totalAmount: 0,
      totalDays: 0,
      
      // 筛选选项
      currentFilter: 'all',
      filterOptions: [
        { label: '全部', value: 'all' },
        { label: '待支付', value: 'pending' },
        { label: '已支付', value: 'paid' },
        { label: '已取消', value: 'cancelled' },
        { label: '已过期', value: 'expired' }
      ],
      
      // 记录列表
      records: [],
      filteredRecords: []
    }
  },
  
  onLoad() {
    this.loadRecords()
    this.loadStats()
  },
  
  onPullDownRefresh() {
    this.refreshData()
  },
  
  methods: {
    /**
     * 加载购买记录
     */
    async loadRecords() {
      if (this.loading) return
      
      this.loading = true
      this.loadStatus = 'loading'
      
      try {
        const params = {
          page: this.page,
          page_size: this.pageSize,
          status: this.currentFilter === 'all' ? '' : this.getStatusValue(this.currentFilter)
        }
        
        const result = await getVipOrders(params)
        
        if (this.page === 1) {
          this.records = result.data || []
        } else {
          this.records = [...this.records, ...(result.data || [])]
        }
        
        this.hasMore = result.has_more || false
        this.filterRecords()
        
      } catch (error) {
        console.error('加载VIP记录失败:', error)
        this.$u.toast('加载失败，请重试')
      } finally {
        this.loading = false
        this.loadStatus = this.hasMore ? 'loadmore' : 'nomore'
        uni.stopPullDownRefresh()
      }
    },
    
    /**
     * 加载统计数据
     */
    async loadStats() {
      try {
        const result = await getVipOrders({ stats: true })
        this.totalOrders = result.total_orders || 0
        this.totalAmount = result.total_amount || 0
        this.totalDays = result.total_days || 0
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    
    /**
     * 刷新数据
     */
    refreshData() {
      this.page = 1
      this.hasMore = true
      this.loadRecords()
      this.loadStats()
    },
    
    /**
     * 加载更多
     */
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.page++
        this.loadRecords()
      }
    },
    
    /**
     * 切换筛选条件
     */
    changeFilter(filter) {
      if (this.currentFilter === filter) return
      
      this.currentFilter = filter
      this.page = 1
      this.hasMore = true
      this.loadRecords()
    },
    
    /**
     * 筛选记录
     */
    filterRecords() {
      if (this.currentFilter === 'all') {
        this.filteredRecords = this.records
      } else {
        const statusValue = this.getStatusValue(this.currentFilter)
        this.filteredRecords = this.records.filter(record => record.status === statusValue)
      }
    },
    
    /**
     * 获取状态值
     */
    getStatusValue(filter) {
      const statusMap = {
        'pending': 0,
        'paid': 1,
        'cancelled': 2,
        'expired': 3
      }
      return statusMap[filter]
    },
    
    /**
     * 获取状态样式类
     */
    getStatusClass(status) {
      const classMap = {
        0: 'pending',
        1: 'success',
        2: 'cancelled',
        3: 'expired'
      }
      return classMap[status] || 'pending'
    },
    
    /**
     * 获取状态文本
     */
    getStatusText(status) {
      const textMap = {
        0: '待支付',
        1: '已支付',
        2: '已取消',
        3: '已过期'
      }
      return textMap[status] || '未知'
    },
    
    /**
     * 格式化时间
     */
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp * 1000)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    /**
     * 查看订单详情
     */
    viewOrderDetail(record) {
      // 可以跳转到订单详情页面或显示详情弹窗
      console.log('查看订单详情:', record)
    },
    
    /**
     * 继续支付
     */
    async payOrder(record) {
      try {
        uni.showLoading({ title: '发起支付...' })
        
        const result = await requestPayment({
          order_id: record.id,
          order_no: record.order_no
        })
        
        // 调用支付接口
        await uni.requestPayment({
          provider: 'wxpay',
          ...result.payment_params
        })
        
        this.$u.toast('支付成功')
        this.refreshData()
        
      } catch (error) {
        console.error('支付失败:', error)
        this.$u.toast('支付失败，请重试')
      } finally {
        uni.hideLoading()
      }
    },
    
    /**
     * 取消订单
     */
    async cancelOrder(record) {
      try {
        await uni.showModal({
          title: '确认取消',
          content: '确定要取消这个订单吗？',
          confirmText: '确定',
          cancelText: '取消'
        })
        
        uni.showLoading({ title: '取消中...' })
        
        await cancelVipOrder({ order_id: record.id })
        
        this.$u.toast('订单已取消')
        this.refreshData()
        
      } catch (error) {
        if (error.errMsg && error.errMsg.includes('cancel')) {
          return // 用户取消操作
        }
        console.error('取消订单失败:', error)
        this.$u.toast('取消失败，请重试')
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.vip-records {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  
  .page-title {
    color: #fff;
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    display: block;
  }
}

.stats-section {
  margin: 20rpx;
  
  .stats-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    justify-content: space-around;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    
    .stats-item {
      text-align: center;
      
      .stats-value {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .stats-label {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.filter-section {
  margin: 20rpx;
  
  .filter-tabs {
    background: #fff;
    border-radius: 16rpx;
    padding: 10rpx;
    display: flex;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .filter-tab {
      flex: 1;
      text-align: center;
      padding: 16rpx 0;
      border-radius: 12rpx;
      transition: all 0.3s ease;
      
      text {
        font-size: 28rpx;
        color: #666;
      }
      
      &.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        
        text {
          color: #fff;
          font-weight: bold;
        }
      }
    }
  }
}

.records-list {
  margin: 0 20rpx;
  
  .record-item {
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .record-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20rpx;
      
      .record-title {
        display: flex;
        align-items: center;
        
        .vip-type {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-right: 16rpx;
        }
        
        .status-badge {
          padding: 6rpx 16rpx;
          border-radius: 20rpx;
          font-size: 22rpx;
          
          &.pending {
            background: #fff7e6;
            color: #fa8c16;
          }
          
          &.success {
            background: #f6ffed;
            color: #52c41a;
          }
          
          &.cancelled {
            background: #fff2f0;
            color: #ff4d4f;
          }
          
          &.expired {
            background: #f0f0f0;
            color: #999;
          }
        }
      }
      
      .record-time {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .record-content {
      .record-info {
        .info-row {
          display: flex;
          margin-bottom: 12rpx;
          
          .info-label {
            font-size: 28rpx;
            color: #666;
            width: 160rpx;
          }
          
          .info-value {
            font-size: 28rpx;
            color: #333;
            flex: 1;
            
            &.price {
              color: #f4b024;
              font-weight: bold;
            }
          }
        }
      }
      
      .record-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 20rpx;
        gap: 16rpx;
        
        .action-btn {
          padding: 12rpx 24rpx;
          border-radius: 8rpx;
          font-size: 26rpx;
          text-align: center;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #fff;
          
          &.secondary {
            background: #f5f5f5;
            color: #666;
          }
        }
      }
    }
  }
}

.empty-state {
  padding: 100rpx 0;
}

.load-more {
  padding: 40rpx 0;
}
</style>